﻿using System.Globalization;

namespace gixoom.Dom.Converters
{
    internal class HexDigitsStringToBytesConverter: IHexDigitsStringToBytesConverter
    {
        /// <summary>
        /// Converts the specified hexadecimal digits to bytes.
        /// </summary>
        /// <param name="hexDigits">hexadecimal digits</param>
        /// <returns>bytes</returns>
        public byte[] Convert(string hexDigits)
        {
            Ensure.ArgumentNotNull(hexDigits, "hexDigits");

            byte[] result = new byte[(hexDigits.Length + 1) >> 1];

            if (hexDigits.Length % 2 > 0)
            {
                hexDigits = "0" + hexDigits;
            }

            int length = hexDigits.Length;
            int j = 0;

            for (int i = 0; i < length; i += 2)
            {
                string hexDigit = hexDigits.Substring(i, 2);
                int number = int.Parse(hexDigit, NumberStyles.AllowHexSpecifier);
                result[j++] = (byte)number;
            }

            return result;
        }
    }
}
